<template>
  <div class="related-tools">
    <div class="related-header">
      <h3 class="related-title">同类推荐</h3>
      <p class="related-subtitle">发现更多相似工具</p>
    </div>
    
    <div v-if="loading" class="related-loading">
      <div class="loading-spinner"></div>
      <span>加载中...</span>
    </div>
    
    <div v-else-if="relatedTools.length > 0" class="related-list">
      <div 
        v-for="tool in relatedTools" 
        :key="tool.toolId"
        class="related-item"
        @click="handleToolClick(tool)"
      >
        <div class="related-item-icon">
          <CustomImage
            :src="tool.localLogoPath"
            :alt="tool.toolName"
            img-class="lazy-image"
            type="logo"
          />
        </div>
        <div class="related-item-content">
          <h4 class="related-item-title">{{ tool.toolName }}</h4>
          <p class="related-item-desc">{{ tool.description }}</p>
          <div class="related-item-tags">
            <span
              v-for="(tagItem, index) in getProcessedTags(tool.tags.slice(0, 2))"
              :key="`${tagItem.tag}-${index}`"
              class="related-tag"
              :class="[tagItem.color.bgColor, tagItem.color.textColor]"
            >
              {{ tagItem.tag }}
            </span>
          </div>
        </div>
      </div>
    </div>
    
    <div v-else class="related-empty">
      <p>暂无相关工具推荐</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { ToolItem } from '~/types/tools'
import { processToolTags, type TagColorCombination } from '~/components/ToolCard/toolUtils'

interface Props {
  /** 当前工具的分类ID */
  categoryId: number
  /** 当前工具的ID（用于排除自身） */
  currentToolId: number
  /** 显示数量限制 */
  limit?: number
}

const props = withDefaults(defineProps<Props>(), {
  limit: 6
})

const relatedTools = ref<ToolItem[]>([])
const loading = ref(true)

/**
 * 获取同类工具
 * 根据分类ID获取相关工具，排除当前工具
 */
const fetchRelatedTools = async () => {
  try {
    loading.value = true
    
    // 获取同类工具数据
    const { success, data } = await $fetch('/api/tools-with-tags', {
      method: 'POST',
      body: {
        categoryIds: [props.categoryId],
        all: true
      }
    })
    
    if (success && data && data.length > 0 && data[0]?.list) {
      // 获取第一个分类的工具列表，并排除当前工具
      const tools = data[0].list.filter(tool => tool.toolId !== props.currentToolId)
      // 随机选择指定数量的工具
      relatedTools.value = tools.sort(() => Math.random() - 0.5).slice(0, props.limit)
    }
  } catch (error) {
    console.error('获取同类工具失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 处理工具标签显示
 */
const getProcessedTags = (tags: string[]): Array<{tag: string, color: TagColorCombination}> => {
  return processToolTags(tags, true)
}

/**
 * 点击工具跳转
 */
const handleToolClick = (tool: ToolItem) => {
  navigateTo(`/tool-detail/${tool.toolId}`)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchRelatedTools()
})

// 监听props变化，重新获取数据
watch(() => [props.categoryId, props.currentToolId], () => {
  fetchRelatedTools()
})
</script>

<style lang="less" scoped>
.related-tools {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  }
}

.related-header {
  margin-bottom: 20px;
}

.related-title {
  font-size: 20px;
  font-weight: 700;
  color: #333;
  margin-bottom: 4px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.related-subtitle {
  font-size: 14px;
  color: #666;
}

.related-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  flex-direction: column;
  gap: 12px;
}

.loading-spinner {
  width: 24px;
  height: 24px;
  border: 2px solid #f3f3f3;
  border-top: 2px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.related-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.related-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
  
  &:hover {
    background: rgba(102, 126, 234, 0.05);
    border-color: rgba(102, 126, 234, 0.2);
    transform: translateX(4px);
  }
}

.related-item-icon {
  flex-shrink: 0;
  width: 40px;
  height: 40px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.related-item-content {
  flex: 1;
  min-width: 0;
}

.related-item-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.related-item-desc {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
  margin-bottom: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.related-item-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.related-tag {
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 10px;
  font-weight: 500;
}

.related-empty {
  text-align: center;
  padding: 40px 20px;
  color: #999;
  font-size: 14px;
}

// 暗黑模式
html.dark .related-tools {
  background: var(--bg-header);
  border: 1px solid var(--border-color);
}

html.dark .related-title {
  background: var(--btn-primary-bg);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

html.dark .related-subtitle {
  color: var(--text-secondary);
}

html.dark .related-item {
  &:hover {
    background: var(--bg-hover);
    border-color: var(--primary-color);
  }
}

html.dark .related-item-title {
  color: var(--text-color);
}

html.dark .related-item-desc {
  color: var(--text-secondary);
}

html.dark .related-empty {
  color: var(--text-light);
}

// 响应式设计
@media (max-width: 1024px) {
  .related-tools {
    margin-top: 24px;
  }
}

@media (max-width: 768px) {
  .related-tools {
    padding: 20px;
  }
  
  .related-title {
    font-size: 18px;
  }
  
  .related-item-icon {
    width: 36px;
    height: 36px;
  }
  
  .related-item-title {
    font-size: 13px;
  }
  
  .related-item-desc {
    font-size: 11px;
  }
}
</style>